const Koa = require("koa");
const Router = require("@koa/router");
const bodyParser = require("koa-bodyparser");
const { PrismaClient } = require("@prisma/client");
// https://juejin.cn/post/7231152303583100988?searchId=20231117094958E353B7A0F34632AD5258

const prisma = new PrismaClient();
prisma.$connect().catch((err) => console.log(err));
const app = new Koa();

const userRouter = new Router({
  prefix: "/users",
});
const articleRouter = new Router({
  prefix: "/articles",
});

app.use(bodyParser());

userRouter.get("/", async (ctx) => {
  const users = await prisma.user.findMany({ where: {} });
  ctx.body = users;
});

userRouter.get("/:id", async (ctx) => {
  const id = parseInt(ctx.params.id);
  const user = await prisma.user.findUnique({
    where: { id },
  });
  ctx.body = user;
});

userRouter.post("/", async (ctx) => {
  const user = ctx.request.body;
  const newUser = await prisma.user.create({ data: user });
  ctx.body = newUser;
});

userRouter.patch("/:id", async (ctx) => {
  const id = parseInt(ctx.params.id);
  const updateUser = ctx.request.body;
  const user = await prisma.user.update({
    where: {
      id,
    },
    data: updateUser,
  });
  ctx.body = user;
});

userRouter.delete("/:id", async (ctx) => {
  const id = parseInt(ctx.params.id);
  const user = await prisma.user.delete({
    where: { id },
  });
  ctx.body = user;
});

articleRouter.post("/", async (ctx) => {
  const user = await prisma.user.findFirst();
  const newUser = await prisma.post.create({
    data: {
      title: "第一篇文章",
      desc: "第一篇文章的描述",
      content: "第一篇文章的内容",
      authorId: user.id,
    },
  });
  ctx.body = newUser;
});

articleRouter.get("/", async (ctx) => {
  const posts = await prisma.post.findMany({
    where: {},
    include: {
      author: true
    }
  });
  ctx.body = posts;
});

app.use(userRouter.routes()).use(userRouter.allowedMethods());
app.use(articleRouter.routes()).use(articleRouter.allowedMethods());

app.listen(3000, () => console.log("http://localhost:3000"));
